package com.gitee.hermer.engine.jars.core.event.listener;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;

import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.engine.jars.core.event.EngineHandleEvent;
import com.gitee.hermer.engine.jars.core.event.storage.IEngineHandleEventStorage;

public abstract class EngineEventListener<E extends EngineHandleEvent> extends UtilsContext implements ApplicationListener<E>,ApplicationContextAware{
	
	
	protected ApplicationContext parentContext;
	


	@Autowired
	private IEngineHandleEventStorage<E> storage;

	@Override
	public void onApplicationEvent(E event) {
		if(!storage.containsEvent(event)){
			try{
				storage.beginEvent(event);
				onEvent(event);
			}catch (Exception e) {
				error(e.getMessage(),e);
			}finally{
				storage.endEvent(event);
			}
		}else{
			error("重复的事件类型 -> [%s]",event.toString());
		}
	}

	public abstract void onEvent(E event);
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.parentContext = applicationContext;
	}

}
